package k4_thread.demo08;

public class ThreadCommunicate {
    public static void main(String[] args) {

        DessertShop dessertShop = new DessertShop(10);

        new Thread(()-> {
            while (true){
                dessertShop.makeBread();
            }
        },"面包师").start();

        new Thread(()-> {
            while (true){
                dessertShop.saleBread();
            }
        },"销售员").start();

    }
}

class DessertShop{

    int totalBread;

    int tmpBread;

    public DessertShop(int totalBread) {
        this.totalBread = totalBread;
    }

    /**
     * 制作面包
     */
    public synchronized void makeBread(){
        try {
            System.out.println("开始制作面包");
            //如果当前做出来的面包数没有达到总数量，继续做面包
            while(tmpBread<totalBread){
                System.out.println(Thread.currentThread().getName()+"制作了一个面包，" +
                        "现在有"+ ++tmpBread+"个面包");
                Thread.sleep(300);
            }
            System.out.println(totalBread+"个面包已经制作完毕，可以售卖");
            notify();
            wait();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 售卖面包
     */
    public synchronized void saleBread(){
        try {
            //如果当前剩余面包数大于0 ，可以进行售卖
            if(tmpBread>0){
                System.out.println(Thread.currentThread().getName()+"卖了一个面包，还剩"+ --tmpBread +"个面包");
                Thread.sleep(500);
            }else{
                System.out.println("面包已售罄");
                notify();
                wait();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
